<template>
	<view class="page-container">
		<view class="top-container">
			<view class="date_change">
				<view class="datebox" v-for="(item, index) in dateList" :key="index" @click="changeDate(index)"
					:class="{ 'visited-color': visitedIndex === index }">
					<view class="date-content">
						<view class="date-select">
							<view class="date">{{ item.date }}</view>
							<view class="day">{{ item.day.value }}</view>
						</view>
					</view>
				</view>
			</view>

			<view>
				<view class="meals-box" v-for="(meal, index) in ['breakfast', 'lunch', 'dinner', 'shop']" :key="index"
					v-if="shouldShowMeal(currentDateItem, meal)" @click="changeMeal(meal)"
					:class="{ 'highlighted-meal': currentMeal === meal }">
					{{ mealMap[meal] }}
				</view>
			</view>
		</view>

		<view v-if="currentMeal && mealTimeMap[currentMeal]" class="meal-time-info">
			<view v-for="(item, index) in mealTimeMap[currentMeal]" :key="index" class="meal-time-text">
				点餐时间：{{ item.order }} 送餐时间：{{ item.delivery }}
			</view>
		</view>

		<view class="active-box-container">
			<view v-if="fastfood.length > 0" class="tabs_content">
				<chainTabs :list="fastfood" :name="fastfood.name" :height="height" @add="onAdd" @decrease="decrease"
					@detailCheck="detailCheck" />
			</view>
			<view v-if="goods.length > 0" class="tabs_content">
				<chainTabs :list="goods" :name="goods.name" :height="height" @add="onAdd" @decrease="decrease" />
			</view>
			<!-- <uv-empty v-else mode="data" icon="https://cdn.uviewui.com/uview/empty/data.png" text="餐段已无菜品"></uv-empty> -->
		</view>
		<uv-popup ref="popup" mode="bottom" custom-style="height: 72vh;" :closeOnClickOverlay="false" round="12">
			<ShopCartSticky :item="detail" @close="close" @submit="submitDetail"/>
		</uv-popup>
	</view>
</template>


<script>
	import {
		formDate
	} from "@/common/js/formDate.js";
	import {
		mapActions,
		mapGetters
	} from "vuex";
	import chainTabs from "@/component/chain-tabs.vue";
	import ShopCartSticky from "@/component/shop-cart-sticky.vue";
	import schedule from "@/assets/schedule.json";
	import goods from "@/assets/goods.json";

	export default {
		components: {
			chainTabs,
			ShopCartSticky,
		},
		data() {
			return {
				dailyMeals: {}, // 每日的餐单副本
				cachedMeals: {}, // 用于缓存的餐单数据
				currentMeal: "", // 当前选择的餐段
				currentDateItem: {}, // 当前选择的日期
				fastfood: [],
				goods: [],
				visitedIndex: 0,
				dateList: [],
				currentDateItem: {},
				currentMeal: "",
				mealMap: {
					breakfast: "早餐",
					lunch: "午餐",
					dinner: "晚餐",
					shop: "商店"
				},
				mealTimeMap: {
					breakfast: {
						time: {
							order: "00:00-23:00",
							delivery: "07:00-08:00"
						}
					},
					lunch: {
						time: {
							order: "00:00-23:59",
							delivery: "11:00-12:00"
						}
					},
					dinner: {
						time: {
							order: "00:00-23:59",
							delivery: "17:00-18:00"
						}
					}
				},
				detail: ''
			}
		},

		onLoad() {
			this.initialize();
			this.getTotalCount()
		},

		computed: {
			...mapGetters(["cartItems", "totalCount"]),
			height() {
				// 获取屏幕高度
				const windowHeight = uni.getSystemInfoSync().windowHeight;
				const baseHeight = 149
				const mealTimeHeight = this.currentMeal && this.mealTimeMap[this.currentMeal] ? 37 : 0;

				return windowHeight - baseHeight - mealTimeHeight;
			},
		},

		watch: {
			cartItems: {
				handler(cartItems) {
					if (!this.currentMeal) return;

					const currentDateKey =
						`${String(this.currentDateItem.year)}-${String(this.currentDateItem.month).padStart(2, "0")}-${String(this.currentDateItem.date).padStart(2, "0")}`;

					if (this.fastfood.length > 0) {
						this.fastfood.forEach((item) => {
							item.childrens.forEach((child) => {
								const cartItem = cartItems.find(
									(cart) =>
									cart.mealType === this.mealMap[this.currentMeal] &&
									cart.date === currentDateKey
								);

								if (cartItem) {
									const product = cartItem.products.find(
										(product) => product.id === child.id
									);
									if (product) {
										child.count = product.count;
									}
								}
							});
						});
					}
				},
				deep: true,
				immediate: true
			}
		},

		methods: {
			...mapActions(["addCartItems", "decreaseCartItems"]),
			initialize() {
				this.dateList = formDate(new Date(), "week-date");
				const defaultIndex = 0; // 默认选择当天
				this.changeDate(defaultIndex);

				// 检查当天是否还有可选餐段，如果没有，切换到商店模式
				const defaultMeal = this.getDefaultMeal(this.dateList[defaultIndex]);
				if (!defaultMeal) {
					this.changeMeal("shop");
				}
			},

			changeDate(index) {
				this.visitedIndex = index;
				this.currentDateItem = this.dateList[index];
				this.generateDailyMeals(); // 动态生成独立的每日餐单
				// 检查当日默认餐段，如果没有可选餐段则高亮商店
				const defaultMeal = this.getDefaultMeal(this.currentDateItem);
				this.changeMeal(defaultMeal || "shop");
			},

			getDefaultMeal(dateItem) {
				const now = new Date();
				const dayStart = new Date(dateItem.year, dateItem.month - 1, dateItem.date);

				const mealCutoffs = {
					breakfast: 1,
					lunch: 10,
					dinner: 16,
				};
				for (const [meal, hour] of Object.entries(mealCutoffs)) {
					if (now <= new Date(dayStart.getTime() + hour * 3600000)) return meal;
				}
				return null;
			},

			shouldShowMeal(item, mealType) {
				const now = new Date();
				const dayStart = new Date(item.year, item.month - 1, item.date);

				if (mealType === "shop") {
					// 商店只在当日显示
					return (
						now.getFullYear() === dayStart.getFullYear() &&
						now.getMonth() === dayStart.getMonth() &&
						now.getDate() === dayStart.getDate()
					);
				}
				const mealCutoffs = {
					breakfast: 3,
					lunch: 10,
					dinner: 16,
				};
				const mealEnd = new Date(dayStart.getTime() + mealCutoffs[mealType] * 3600000);

				return now < dayStart || (now >= dayStart && now <= mealEnd);
			},

			generateDailyMeals() {
				const today = new Date();
				const mealsByDate = {};

				for (let i = 0; i < 3; i++) {
					const currentDate = new Date(today);
					currentDate.setDate(today.getDate() + i); // 当天及未来两天

					const formattedDate = `${currentDate.getFullYear()}-${String(
			        currentDate.getMonth() + 1
			      ).padStart(2, "0")}-${String(currentDate.getDate()).padStart(2, "0")}`;

					mealsByDate[formattedDate] = JSON.parse(JSON.stringify(schedule.meal_list)); // 创建餐单副本
				}

				this.dailyMeals = mealsByDate; // 保存生成的独立餐单
			},

			changeMeal(mealType) {
				this.currentMeal = mealType;

				const currentDateKey = `${this.currentDateItem.year}-${String(
				      this.currentDateItem.month
				    ).padStart(2, "0")}-${String(this.currentDateItem.date).padStart(2, "0")}`;

				if (mealType === "shop") {
					// 处理 shop 的逻辑
					this.fastfood = []; // 清空其他餐段的数据
					this.goods = this.mergeWithCartItems(goods.list, mealType, currentDateKey); // 加载 goods.json 中的商店商品列表
					return;
				}

				if (!mealType) {
					this.fastfood = [];
					this.goods = []; // 清空商店商品数据
					return;
				}

				// 检查缓存
				if (!this.cachedMeals[currentDateKey]) {
					this.cachedMeals[currentDateKey] = {};
				}

				if (!this.cachedMeals[currentDateKey][mealType]) {
					// 如果没有缓存，初始化默认值
					const selectedMeal = this.dailyMeals[currentDateKey]?.find(
						(meal) => meal.name === this.mealMap[mealType]
					);
					this.cachedMeals[currentDateKey][mealType] = selectedMeal ?
						JSON.parse(JSON.stringify(selectedMeal.list)) : [];
				}

				// 从缓存加载数据并与 Vuex 的购物车数据合并
				this.fastfood = this.mergeWithCartItems(
					this.cachedMeals[currentDateKey][mealType],
					mealType,
					currentDateKey
				);
				this.goods = [];
			},

			mergeWithCartItems(items, mealType, currentDateKey) {
				return items.map((item) => {
					return {
						...item,
						childrens: item.childrens.map((child) => {
							// 如果 mealType 是 "shop"，直接返回原来的 child，不做任何处理
							if (mealType === "shop") {
								const cartItem = this.cartItems.find(
									(cart) =>
									cart.mealType === this.mealMap[mealType]
								);

								// 在 cartItem 的 products 中查找对应的 child
								const product = cartItem?.products.find((p) => p.id === child.id);

								return {
									...child,
									count: product ? product.count : 0, // 使用购物车中的 count 或默认值 0
								};
							} else {
								const cartItem = this.cartItems.find(
									(cart) =>
									cart.mealType === this.mealMap[mealType] &&
									cart.date === currentDateKey
								);

								// 在 cartItem 的 products 中查找对应的 child
								const product = cartItem?.products.find((p) => p.id === child.id);

								return {
									...child,
									count: product ? product.count : 0, // 使用购物车中的 count 或默认值 0
								};
							}
						}),
					};
				});
			},

			// 添加商item品
			onAdd(item) {
				console.log('增加',item)
				// 获取当前日期
				const currentDate =
					`${this.currentDateItem.year}-${String(this.currentDateItem.month).padStart(2, '0')}-${String(this.currentDateItem.date).padStart(2, '0')}`;

				// 获取当前日期是星期几
				const weekDay = new Date(this.currentDateItem.year, this.currentDateItem.month - 1, this.currentDateItem
					.date).getDay();
				// 构建 payload 对象
				const payload = {
					date: currentDate, // 当前日期
					mealType: this.mealMap[this.currentMeal], // 当前餐类
					time: this.mealTimeMap[this.currentMeal]?.time.delivery || '', // 送餐时间
					weekDay: weekDay, // 当前星期几 (0-6, 0 是星期天，6 是星期六)
					orderTime: this.mealTimeMap[this.currentMeal]?.time.order || '', // 点餐时间
					products: [] // 存放餐类下的所有产品
				};

				// 假设 item 是一个包含多个产品的对象，每个产品都有 id、image、name、count 等信息
				item.forEach(product => {
					// 为每个产品创建一个对应的对象
					const productPayload = {
						id: product.id,
						image: product.image,
						name: product.name,
						selected: product.selected,
						price: product.price,
						count: product.count
					};

					// 将每个产品添加到 products 数组中
					payload.products.push(productPayload);
				});

				// 根据操作类型处理购物车
				this.addCartItems(payload); // 将整个 payload 对象传递给购物车
				console.log('payload222',payload)
				// 更新购物车的数量
				this.getTotalCount();
			},

			// 减少商品
			decrease(item) {
				const currentDate =
					`${this.currentDateItem.year}-${String(this.currentDateItem.month).padStart(2, '0')}-${String(this.currentDateItem.date).padStart(2, '0')}`;

				// 获取当前日期是星期几
				const weekDay = new Date(this.currentDateItem.year, this.currentDateItem.month - 1, this.currentDateItem
					.date).getDay();

				// 更新商品数量后，检查是否需要删除数量为 0 的商品
				item = item.filter((goods) => goods.count > 0); // 删除数量为 0 的商品

				// 构建 payload 对象
				const payload = {
					date: currentDate, // 当前日期
					mealType: this.mealMap[this.currentMeal], // 当前餐类
					time: this.mealTimeMap[this.currentMeal]?.time.delivery || '', // 送餐时间
					weekDay: weekDay, // 当前星期几 (0-6, 0 是星期天，6 是星期六)
					orderTime: this.mealTimeMap[this.currentMeal]?.time.order || '', // 点餐时间
					products: [] // 存放餐类下的所有产品
				};

				// 遍历每个商品
				item.forEach(product => {
					// 为每个产品创建一个对应的对象
					const productPayload = {
						id: product.id,
						image: product.image,
						name: product.name,
						selected: product.selected,
						price: product.price,
						count: product.count
					};

					// 将每个产品添加到 products 数组中
					payload.products.push(productPayload);
				});
				this.decreaseCartItems(payload);

				// 更新购物车的数量
				this.getTotalCount();
			},

			getTotalCount() {
				console.log('this.totalCount', this.totalCount);
				console.log('this.cartItems', this.cartItems);
				// 更新 tabBarBadge
				if (this.totalCount > 0) {
					uni.setTabBarBadge({
						index: 1, // tabBar 索引
						text: this.totalCount.toString(), // 使用 Vuex 中的商品总数
					});
				} else {
					// 当 totalCount 为 0 时，移除 badge
					uni.removeTabBarBadge({
						index: 1,
					});
				}
			},

			detailCheck(item) {
				console.log('item',item)
				this.detail = item
	
				this.$refs.popup.open()
				uni.hideTabBar()
			},
			close() {
				this.$refs.popup.close();
				setTimeout(() => {
					uni.showTabBar()
				}, 300)
			},
			 submitDetail(updatedItem) {
			    console.log('接收传过来的count值', updatedItem);
			    // 你可以在这里处理 updatedItem，例如更新购物车、重新渲染等
				
				const currentDate =
					`${this.currentDateItem.year}-${String(this.currentDateItem.month).padStart(2, '0')}-${String(this.currentDateItem.date).padStart(2, '0')}`;
				
				// 获取当前日期是星期几
				const weekDay = new Date(this.currentDateItem.year, this.currentDateItem.month - 1, this.currentDateItem
					.date).getDay();
					
				// 构建 payload 对象
				const payload = {
					date: currentDate, // 当前日期
					mealType: this.mealMap[this.currentMeal], // 当前餐类
					time: this.mealTimeMap[this.currentMeal]?.time.delivery || '', // 送餐时间
					weekDay: weekDay, // 当前星期几 (0-6, 0 是星期天，6 是星期六)
					orderTime: this.mealTimeMap[this.currentMeal]?.time.order || '', // 点餐时间
					products: [] // 存放餐类下的所有产品
				};
				const productPayload = updatedItem
				
				payload.products.push(productPayload);
				
				console.log('payload',payload)
				this.addCartItems(payload);
				
				// 更新购物车的数量
				this.getTotalCount();
				
				this.$refs.popup.close();
				setTimeout(() => {
					uni.showTabBar()
				}, 300)
			  }
		}
	}
</script>

<style scoped lang="scss">
	.page-container {
		position: fixed;
		width: 100%;

		.date_change {
			background-color: #ffffff;
			overflow: hidden;

			.datebox {
				width: calc(20% - 48rpx);
				text-align: center;
				display: inline-block;
				border: 2rpx solid #cdcdcd;
				margin: 12rpx;
				padding: 12rpx;
				border-radius: 12rpx;
				background-color: #ffffff;
			}

			.visited-color {
				background: linear-gradient(180deg, #418ec7, #0b6eef);
				border: 2rpx solid #c9c9c9;

				.date {
					color: #ffffff !important;
				}

				.day {
					color: #ffffff !important;
				}
			}

			.date-select {
				padding: 16rpx 0;

				.date {
					align-items: flex-end;
					line-height: 48rpx;
					font-size: 40rpx;
					font-weight: 500;
					color: #333333;
				}

				.day {
					font-size: 28rpx;
					color: #888888;
				}

				.status {
					line-height: 36rpx;
					font-size: 28rpx;
					font-weight: 400;
				}
			}
		}

		.meals-box {
			display: inline-block;
			width: calc(20% - 48rpx);
			text-align: center;
			padding: 20rpx 12rpx;
			border: 2rpx solid #c9c9c9;
			border-radius: 12rpx;
			margin: 12rpx;
			color: #333333;
			background-color: #ffffff;
			font-size: 28rpx;
		}

		.highlighted-meal {
			background-color: #1975ed;
			color: white;
			font-weight: bold;
			border: 2rpx solid #1975ed;
			color: #ffffff;
		}

		.active-box-container {
			position: relative;
			background-color: #ffffff;
			border-radius: 24rpx 24rpx 0 0;
			z-index: 0;
		}

		.meal-time-info {
			background-color: #d5e8ff;
			padding: 16rpx 24rpx;

			.meal-time-text {
				font-size: 28rpx;
				color: #333333;
			}
		}
	}
</style>